// @ts-ignore
import common from '@/router/modules/common'
// import home, {routes} from '@/router/home'
import {useStore} from '@/store/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {createRouter, createWebHistory} from 'vue-router'
import XEUtils from 'xe-utils'

const matchRouter = (_routers: Array<any>, path) => {
	let findRouterByPath = null
	const deepFind = (_r, p) => {
		for (let i = 0; i < _r.length; i++) {
			if (_r[i].path === p) {
				findRouterByPath = _r[i]
				return
			}
			if (_r[i].children) {
				deepFind(_r[i].children, p)
			}
		}
	}
	deepFind(_routers, path)
	return findRouterByPath
}

const router = createRouter({
	history: createWebHistory(),
	// routes: [home, ...common]
	routes: [ ...common]
})

export default router

// 路由是否已生成
let routeHasGenerated = false
// 是否来自微信小程序的跳转
let isFormWx = false
let WxTargetPath: any = null

router.beforeEach((to, from, next) => {
	NProgress.start()

	const {meta} = to
	const store = useStore()
	document.title = meta.title || import.meta.env.VITE_TITLE

	// 如果从小程序端进入的 解析下列参数
	const {searchQuery} = XEUtils.parseUrl(location)

	if (searchQuery.token && searchQuery.path && searchQuery.phone) {
		isFormWx = true
		// WxTargetPath = matchRouter(routes, searchQuery.path)
		store.permissions = WxTargetPath.meta?.permissions || []
		store.accessToken = searchQuery.token
		store.isFormWx = true
		store.currentUser.phone = searchQuery.phone
	}
	if (searchQuery.token && searchQuery.path && searchQuery.from) {
		store.accessToken = searchQuery.token
		store.userLoginByToken({
			token: searchQuery.token,
			path: searchQuery.path
		})
	}

	if (meta.target === '_blank' && Object.keys(from.meta).length) {
		window.open(to.fullPath, meta.target)
		NProgress.done()
	} else {
		if (common.map(o => o.path).includes(to.path)) {
			if (isFormWx) return next(WxTargetPath.path)
			return next()
		} else if (store.accessToken) {
			if (!routeHasGenerated) {
				generatorRoutes()
				router.replace(isFormWx ? WxTargetPath : to).then(() => {
					console.log('动态路由处理完毕，更新页面')
				})
			} else {
				next()
			}
		} else {
			next('/login')
		}
	}
})

router.afterEach(() => {
	NProgress.done()
})

/**
 * 根据后台返回的菜单生成对应的路由
 * @param paths
 */
export const generatorRoutes = () => {
	// 刷新路由重定向
	// refreshRoutes(routes)

	// // 设置子路由
	// home.children = routes
	// const first: any = routes.find((o: any) => !o.meta.hidden) || {}

	// // 首页重定向至第一个可见页面
	// home.redirect = first.path

	// // 更新路由
	// router.addRoute(home)

	routeHasGenerated = true
}

/**
 * 更新路由重定向
 * @param routes
 */
const refreshRoutes = (routes: any[]) => {
	const store = useStore()

	for (const route of routes) {
		const children = route.children || []

		if (!route.meta.hidden) {
			const hasPermissions = store.hasPermissions(route.meta.permissions)
			// 无权限访问，隐藏菜单并重定向至404页面
			if (!hasPermissions) {
				route.redirect = '/404'
				route.meta.hidden = !hasPermissions
			}

			if (children && children.length) {
				refreshRoutes(children)
				// 重定向至第一个可见子菜单，无子菜单则重定向至404
				const first = children.find((o: any) => !o.meta.hidden) || {path: '/404'}

				route.redirect = first.path
				// route.meta.hidden = !first.name
			}
		}
	}
}
